//
//  HomeViewController.m
//  KTVShopProduct
//
//  Created by paeanSs on 2017/11/7.
//  Copyright © 2017年 paeanSs. All rights reserved.
//

#import "HomeViewController.h"

#import "KTSearchBar.h"
#import "KTRegionBtnView.h"
#import "SDCycleScrollView.h"
#import "StoreCell.h"
#import "HomeSectionView.h"
#import "RecommendCell.h"


#import "UIView+TapGestureRecognizer.h"




@interface HomeViewController ()<SDCycleScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource>
#pragma mark -数据源
//新成员
@property (nonatomic, strong) NSMutableArray *memberArrM;
//门店活动
@property (nonatomic, strong) NSMutableArray *activityArrM;
//section
@property (nonatomic, strong) NSArray *sectionArrM;
//推荐门店
@property (nonatomic, strong) NSMutableArray *recommendArrM;

#pragma mark -view
//搜索框
@property (nonatomic, strong) KTSearchBar *searchBar;
//地区选择btnView
@property (nonatomic, strong) KTRegionBtnView *regionView;
//门店选择btn
@property (nonatomic, strong) UILabel *storeLabel;

//背景scroll
@property (nonatomic, strong) UIScrollView *bgScrollView;

//轮播图
@property (nonatomic, strong) SDCycleScrollView *bannerView;
//门店新成员
@property (nonatomic, strong) UICollectionView *memberCollectionView;
//推荐门店
@property (nonatomic, strong) UITableView *recommendTblView;

//没有更多信息
@property (nonatomic, strong) UILabel *noMoreLbl;



@end

@implementation HomeViewController

- (NSMutableArray *)memberArrM{
    if (!_memberArrM) {
        _memberArrM = [NSMutableArray array];
    }
    return _memberArrM;
}

- (NSMutableArray *)activityArrM{
    if (!_activityArrM) {
        _activityArrM = [NSMutableArray array];
    }
    return _activityArrM;
}

- (NSMutableArray *)recommendArrM{
    if (!_recommendArrM) {
        _recommendArrM = [NSMutableArray array];
    }
    return _recommendArrM;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupNav];
    [self setupSubViews];
}

- (void)setupNav{
    self.title = @"首页";
    
    
}

- (void)setupSubViews{

    
    CGFloat rightWidth = 15;
    WEAKSELF
    self.regionView = [[KTRegionBtnView alloc] initWithTitle:@"上海"];
    [self.view addSubview:self.regionView];
    [self.view addTapGestureRecognizerWithDelegate:self Block:^(NSInteger tag) {
        [weakSelf  regionBtnClick];
    }];
    
    [self.regionView setTitle:@"上海" withSuperView:self.view];
    
    
    self.storeLabel = [[UILabel alloc] init];
    self.storeLabel.textAlignment = NSTextAlignmentLeft;
    self.storeLabel.text = @"选择门店";
    self.storeLabel.font = [UIFont systemFontOfSize:15];
    self.storeLabel.textColor = [UIColor blackColor];
    [self.storeLabel sizeToFit];
    [self.view addSubview:self.storeLabel];
    
    [self.storeLabel addTapGestureRecognizerWithDelegate:self Block:^(NSInteger tag) {
        [weakSelf storeBtnClick];
    }];
    
    
    [self.storeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.storeLabel);
        make.right.equalTo(self.view).offset(-rightWidth);
        make.centerY.height.equalTo(self.regionView);
        
    }];

    self.searchBar = [[KTSearchBar alloc] init];
    self.searchBar.placeholder = @"请输入名称、地址";
    [self.view addSubview:self.searchBar];
    
    
    self.bgScrollView = [[UIScrollView alloc] init];
    self.bgScrollView.contentSize = CGSizeMake(KTScreenWidth, KTScreenHeight * 2);
    self.bgScrollView.showsVerticalScrollIndicator = NO;
    self.bgScrollView.backgroundColor = UIColorFromHex(0xeeeeee);
    [self.view addSubview:self.bgScrollView];
    
    [self.bgScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.width.equalTo(self.view);
        make.top.equalTo(self.searchBar.mas_bottom);
        make.bottom.equalTo(self.view);
    }];
    
    NSArray * localizationImagesGroup = @[[UIImage imageNamed:@"img_platform_home_rotation"],[UIImage imageNamed:@"img_platform_home_store_one"],[UIImage imageNamed:@"img_platform_home_store_two"],[UIImage imageNamed:@"img_platform_home_store_three"]];
    self.bannerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, KTScreenWidth, KTScreenWidth/2.0) imagesGroup:localizationImagesGroup];

    self.bannerView.delegate = self;
    self.bannerView.autoScrollTimeInterval = 5.;// 自动滚动时间间隔
    self.bannerView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;// 翻页 右下角
    self.bannerView.titleLabelBackgroundColor = [UIColor clearColor];// 图片对应的标题的 背景色。（因为没有设标题)
    [self.bgScrollView addSubview:self.bannerView];
    self.bannerView.dotColor = UIColorFromHex(0xd0a44d);

    [self.bannerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(KTScreenWidth, KTScreenWidth/2.0));
        make.centerX.top.equalTo(self.bgScrollView);
    }];
    
    //    CGFloat spaceW = 24;
    CGFloat collectionW = KTScreenWidth/2.0;
    CGFloat collectionH = collectionW/375.0 * 342.0;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(collectionW, collectionH);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
//    layout.headerReferenceSize=CGSizeMake(self.view.frame.size.width, 20); //设置collectionView头视图的大小
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);

    self.memberCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.memberCollectionView.delegate = self;
    self.memberCollectionView.dataSource = self;
    self.memberCollectionView.scrollEnabled = NO;
    self.memberCollectionView.backgroundColor = [UIColor whiteColor];
    [self.bgScrollView addSubview:self.memberCollectionView];
    self.memberCollectionView.showsVerticalScrollIndicator = NO;
    self.memberCollectionView.showsHorizontalScrollIndicator = NO;
    [self.memberCollectionView registerClass:[StoreCell class] forCellWithReuseIdentifier:StoreCellID];
    [self.memberCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:StoreHeadViewID];
    
    
    self.recommendTblView  = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.recommendTblView.delegate = self;
    self.recommendTblView.dataSource = self;
    self.recommendTblView.backgroundColor = [UIColor whiteColor];
    self.recommendTblView.showsVerticalScrollIndicator = NO;
    self.recommendTblView.scrollEnabled = NO;
    [self.bgScrollView addSubview:self.recommendTblView];
    

  //加载数据
    [self reloadDataSource];
    
    [self.memberCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgScrollView);
        make.width.equalTo(self.view);
        make.top.equalTo(self.bannerView.mas_bottom);
        make.height.mas_equalTo(((self.memberArrM.count/2 + self.memberArrM.count%2) + (self.activityArrM.count/2 + self.activityArrM.count%2)) * collectionH + 2 * SECTION_HEIGHT + 10);
    }];
    
    [self.recommendTblView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(KTScreenWidth, self.recommendArrM.count * RECOMMENDCELL_HEIGHT + SECTION_HEIGHT + 10));
        make.centerX.equalTo(self.bgScrollView);
        make.top.equalTo(self.memberCollectionView.mas_bottom);
    }];
   
    CGFloat noMoreHeight = 44;
    
    self.noMoreLbl = [[UILabel alloc] init];
    self.noMoreLbl.text = @"没有更多信息";
    self.noMoreLbl.textColor = NormalDefalutColor;
    self.noMoreLbl.textAlignment = NSTextAlignmentCenter;
    self.noMoreLbl.font = [UIFont systemFontOfSize:12];
    [self.bgScrollView addSubview:self.noMoreLbl];
    
    [self.noMoreLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(KTScreenWidth, noMoreHeight));
        make.centerX.equalTo(self.bgScrollView);
        make.top.equalTo(self.recommendTblView.mas_bottom);
    }];

}

- (void)reloadDataSource{
    NSArray *titleArrM = @[@"超级玛丽KTV(高桥店)",@"掘金歌城",@"超级玛丽KTV(高桥店)",@"掘金歌城"];
    NSArray *addressArrM = @[@"浦东新区慈善街95号岁金3D广场",@"松江区荣乐东路1819号(松东店)",@"浦东新区慈善街95号岁金3D广场",@"松江区荣乐东路1819号(松东店)"];
    NSArray *imgArrM = @[@"img_platform_home_rotation",@"img_platform_home_store_one",@"img_platform_home_store_two",@"img_platform_home_store_three"];
    for (NSInteger index = 0; index < titleArrM.count; index ++) {
        StoreModel *storeModel = [[StoreModel alloc] init];
        storeModel.url_image = imgArrM[index];
        storeModel.title = titleArrM[index];
       
        storeModel.address = addressArrM[index];
        [self.memberArrM addObject:storeModel];
    }
    NSArray *activityArrM = @[@"掘金歌城松江店举办一年一度会员线下大聚会",@"掘金歌城酒水买一送一"];
    for (NSInteger index = 0; index < activityArrM.count; index ++) {
        StoreModel *storeModel = [[StoreModel alloc] init];
        storeModel.url_image = imgArrM[index];
        storeModel.title = activityArrM[index];
        [self.activityArrM addObject:storeModel];
    }
    
    self.sectionArrM = @[@{@"title":@"门店新成员",@"url_Image":@"home_icon_store"},@{@"title":@"门店活动",@"url_Image":@"Home_icon_activity_normal"},@{@"title":@"推荐门店",@"url_Image":@"home_icon_recommend"}];
    
    RecommendModel *model = [[RecommendModel alloc] init];
    model.title = @"好乐迪(闵行9馆店)";
    model.sales = @"3000";
    model.distance = @"1.3km";
    model.activity = @"酒水满一送一活动";
    model.stars = @"4.5";
    [self.recommendArrM addObject:model];
    [self.recommendArrM addObject:model];
    
    [self.memberCollectionView reloadData];
    [self.recommendTblView reloadData];
}

- (void)regionBtnClick{
    
}

- (void)storeBtnClick{
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    // 获取到约束后的控件frame 以方便写searchBar.frame
    CGFloat regionWidth = self.regionView.frame.size.width;
    CGFloat storeWidth = self.storeLabel.frame.size.width + 15;
    CGFloat searchBarWidth = KTScreenWidth -  (regionWidth > storeWidth? regionWidth:storeWidth) * 2 - 2 * 10;
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(searchBarWidth, 44.0));
        make.top.equalTo(self.regionView);
        make.centerX.equalTo(self.view);
    }];
    
    //重写bgScrollView的contentSize
    CGFloat contentHeight = self.bannerView.frame.size.height + self.memberCollectionView.frame.size.height + self.recommendTblView.frame.size.height + self.noMoreLbl.frame.size.height;
    self.bgScrollView.contentSize = CGSizeMake(KTScreenWidth, contentHeight);
    
}



#pragma mark -UICollectionViewDataSource UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 1) {
        return self.activityArrM.count;
    }else if (section == 0){
        return self.memberArrM.count;
    }
    return 0;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    if([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:StoreHeadViewID forIndexPath:indexPath];
        if(headerView == nil)
        {
            headerView = [[UICollectionReusableView alloc] init];
        }
        headerView.backgroundColor = UIColorFromHex(0xeeeeee);

        if (indexPath.section < self.sectionArrM.count) {
            HomeSectionView  *sectionView = [[HomeSectionView alloc] initWithTitle:self.sectionArrM[indexPath.section][@"title"] url_Image:self.sectionArrM[indexPath.section][@"url_Image"]];
            [headerView addSubview:sectionView];
            [sectionView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.equalTo(headerView);
                make.height.mas_equalTo(SECTION_HEIGHT);
            }];
        }
        
        return headerView;
    }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
        return nil;
    }
    
    return nil;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    StoreCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:StoreCellID forIndexPath:indexPath];
    if (indexPath.item < self.memberArrM.count && indexPath.section == 0) {
        StoreModel *storeModel = self.memberArrM[indexPath.row];
        [cell confiModel:storeModel];
    }else if (indexPath.item < self.activityArrM.count && indexPath.section == 1){
        StoreModel *storeModel = self.activityArrM[indexPath.row];
        [cell configRecommendModel:storeModel];
    }
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
   
    if (section == 1) {
        return CGSizeMake(KTScreenWidth, SECTION_HEIGHT + 10);
    }else
        return CGSizeMake(KTScreenWidth, SECTION_HEIGHT);

}

#pragma mark -UITableViewDataSource UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.recommendArrM.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = RecommendCellID;
    RecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[RecommendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc] init];
    headView.backgroundColor = UIColorFromHex(0xf0f0f0);
    HomeSectionView *sectionView = [[HomeSectionView alloc] initWithTitle:[self.sectionArrM lastObject][@"title"] url_Image:[self.sectionArrM lastObject][@"url_Image"]];
    [headView addSubview:sectionView];
    [sectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(headView);
        make.height.mas_equalTo(SECTION_HEIGHT);
    }];
    return headView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return RECOMMENDCELL_HEIGHT;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return SECTION_HEIGHT + 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
